package cn.com.cetccst.skf;

import android.text.TextUtils;
import android.util.Log;

import com.westone.csr.CmCsrBuilder;
import com.westone.csr.RequestInfo_EX;

import cn.com.cetccst.onlinecert.MdmUserInfo;

public class P10CSRGenerator {

    private static final int SM3_ALG = 1;
    private static final int SIGN_ALG = 0x00020200;

    private CmCsrBuilder csrBuilder;
    private static final String TAG = "P10CSRHelper";

    public interface P10RequestCallback {
        void onGenP10Result(String p10);
    }

    protected P10CSRGenerator() {
        csrBuilder = new CmCsrBuilder();
        csrBuilder.Initialize(SM3_ALG, SIGN_ALG);
    }

    private String getCommonName(MdmUserInfo info) {
        String imei = info.getImei();
        String userName = info.getUserName();
        String phone = info.getPhone();
        String subPhone = "";
        if (!TextUtils.isEmpty(phone) && phone.length() > 4) {
            subPhone = phone.substring(phone.length() - 4).concat("_");
        }
        if (!TextUtils.isEmpty(imei) && imei.length() >= 4) {
            return userName.concat("_").concat(subPhone).concat(imei.substring(imei.length() - 4));
        } else {
            return userName.concat("_").concat(subPhone).concat(imei == null ? "" : imei);
        }
    }

    private RequestInfo_EX getP10requestInfo(MdmUserInfo info) {
        String commonName = getCommonName(info);
        RequestInfo_EX requestInfo = new RequestInfo_EX();
        requestInfo.setCountryName("CN");
        requestInfo.setProvinceName(info.getProvince());
        requestInfo.setCityName(info.getCity());
        requestInfo.setDepartName(info.getOrgName());
        //if (BuildConfig.DEBUG) {
        Log.i(TAG, "mdm user info for requesting cert from server:[" + info.toString() + "]");
        Log.i(TAG, "CommonName:[" + commonName + "]");
        //}

        requestInfo.setCommonName(commonName);
        requestInfo.setOrganizeName(info.getTenantName());
        requestInfo.setEmail(info.getEmail());
        //todo save common name to kv
//        PrefStore.setValue(SCSManager.getInstance().getContext(), "ca_common_name", commonName);
        return requestInfo;
    }

    protected byte[] generatePKCS10(ISkfEntry skfEntry, MdmUserInfo info) {
        byte[] requestHash = csrBuilder.SetParamGenerateHash(getP10requestInfo(info), skfEntry.getPublicKey(true));
        if (requestHash == null) {
            Log.e(TAG, "GeneratePKCS10ReqInfo failed");
            return null;
        }
        byte[] requestSign = skfEntry.sign(requestHash);
        if (requestSign == null) {
            Log.e(TAG, "signECC failed");
            return null;
        }
        return csrBuilder.GenerateReq(requestSign, true);
    }
}
